<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button @click="showAddDialog" type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table border stripe :data="rolesList" style="width: 100%">
        <el-table-column type="expand" width="80">
          <template slot-scope="scope">
            <el-row :class=" [ 'center','b-bottom'  ,i===0?  'b-top':''  ] " v-for="  (item,i) in  scope.row.children" :key="item.id">
              <el-col :span="7">
                <el-tag closable @close="removeTagById(scope.row,item.id)"> {{item.authName}} <i class="el-icon-caret-right"></i> </el-tag>
              </el-col>
              <el-col :span="17">
                <el-row :class=" [i2===0 ?  '' :'b-top' ,'center']   " v-for="  (item2,i2) in item.children" :key="item2.id">
                  <el-col :span="7">
                    <el-tag closable @close="removeTagById(scope.row,item2.id)" type="success"> {{item2.authName}} <i class="el-icon-caret-right"></i> </el-tag>
                  </el-col>
                  <el-col :span="17">
                    <el-tag type="warning" closable @close='removeTagById(scope.row,item3.id)' v-for=" item3  in  item2.children " :key="item3.id"> {{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="80">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="showeditDialog(scope.row.id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button @click="removeRoleById(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button @click="showSetRolesDialog(scope.row) " size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog title="添加角色" @close='addDialogClose' :visible.sync="addDialogVisible" width="50%">
      <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editRolesForm" :rules="editRolesFormRules" ref="editRolesFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" show-checkbox @close='setRolesDialogClose' :visible.sync="setRolesDialogVisible" width="50%">
      <el-tree ref="treeRef" :data="treeList" node-key='id' show-checkbox default-expand-all :default-checked-keys='defKeys' :props="treeProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      addDialogVisible: false,
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      addRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      editRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      },
      setRolesDialogVisible: false,
      treeList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      RolesId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
    },
    addDialogClose() {
      this.$refs.addRolesFormRef.resetFields()
    },
    showAddDialog() {
      this.addDialogVisible = true
    },
    addRoles() {
      this.$refs.addRolesFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败！')
        }
        this.$message.success('添加角色成功！')
        this.getRolesList()
        this.addDialogVisible = false
      })
    },
    async showeditDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }
      this.editRolesForm = res.data
      this.editDialogVisible = true
    },
    async editRoles() {
      this.$refs.editRolesFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put('roles/' + this.editRolesForm.roleId, {
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色信息失败！')
        }
        this.$message.success('修改角色信息成功！')
        this.getRolesList()
        this.editDialogVisible = false
      })
    },
    async removeRoleById(id) {
      const Result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (Result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getRolesList()
    },
    async showSetRolesDialog(row) {
      this.RolesId = row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      this.treeList = res.data
      this.getDefKeys(row, this.defKeys)
      this.setRolesDialogVisible = true
    },
    getDefKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getDefKeys(item, arr)
      })
    },
    setRolesDialogClose() {
      this.defKeys = []
    },
    async setRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      console.log(keys)
      const { data: res } = await this.$http.post(`roles/${this.RolesId}/rights`, {
        rids: keys.join(',')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色权限失败！')
      }
      this.$message.success('分配角色权限成功！')
      this.getRolesList()
      this.setRolesDialogVisible = false
    },
    async removeTagById(row, id) {
      const { data: res } = await this.$http.delete(`roles/${row.id}/rights/` + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色权限失败！')
      }
      row.children = res.data
      this.$message.success('删除角色权限成功！')
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin-top: 5px;
  .el-tag {
    margin: 5px 10px 5px 0;
  }
}
.b-top {
  border-top: 1px solid #eee;
}
.b-bottom {
  border-bottom: 1px solid #eee;
}
.center {
  display: flex;
  align-items: center;
}
</style>
